package com.amap.poi.service.impl;

import com.amap.poi.common.exception.Asserts;
import com.amap.poi.common.result.CodeMsg;
import com.amap.poi.common.utils.RedisUtils;
import com.amap.poi.constant.Constant;
import com.amap.poi.model.dto.PoiDataDTO;
import com.amap.poi.model.req.TextReq;
import com.amap.poi.rpc.AmapCallers;
import com.amap.poi.service.IAmapSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 高德地图搜索 - 业务实现层
 *
 * @author L
 */
@Service
@Slf4j
public class AmapSearchServiceImpl implements IAmapSearchService {

    @Autowired
    private AmapCallers amapCallers;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AsyncServiceImpl asyncService;

    /**
     * 关键词搜索
     *
     * @param req
     * @return
     */
    @Override
    public List<PoiDataDTO> queryByText(TextReq req) {
        // 校验
        if (StringUtils.isBlank(req.getKeywords())) {
            Asserts.fail(CodeMsg.BIND_ERROR.getCode(), "关键词不能为空");
        }
        // 查询缓存
        List lGet = redisUtils.lGet(
                Constant.AMAP_REDIS_TEXT_QUERY_KEY + req.getCity() + "_" + req.getKeywords(), 0, -1
        );
        // 判空
        if (CollectionUtils.isNotEmpty(lGet)) {
            return lGet;
        }
        // 不为空，执行查询
        List<PoiDataDTO> list = amapCallers.initialData(req.getKeywords(), req.getCity());
        // 异步写缓存
        asyncService.asyncSetCache(
                Constant.AMAP_REDIS_TEXT_QUERY_KEY + req.getCity() + "_" + req.getKeywords(), list
        );
        return list;
    }


}
